// pages/safetysenceDeal/safetysenceDeal.js
const app = getApp()
const util = require('../../util/util.js')

Page({
  data: {
    id: 0,
    address: "",
    type: "",
    time: "",
    reporter: "",
    content: "",
    files: [],
    dealFiles: [],
    imageUrl: [],
    contentLength: 0,
    loading: 1,
    reporterWeChatId: "",
    reporterObject:{
      res: "",
      msg: ""
    },
    video:"",
    videoSrc:"",
    dealVideo:"",
    dealVideoSrc:""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let that = this
    dd.httpRequest({
      url: app.baseUrl + '/DingDingSystem/getSafetySceneById',
      method: 'POST',
      headers: {
        "Content-Type": "application/json"
      },
      data: JSON.stringify({
        id: parseInt(options.id),
      }),
      dataType: 'json',
      success: res => {
        let photo = []
        if (res.data.photo == "" || res.data.photo == null) {
          photo.push("/images/nophoto.png")
        } else if (res.data.photo.split(',')) {
          for (let i = 0; i < res.data.photo.split(',').length; i++) {
            photo.push(app.imageUrl + res.data.photo.split(',')[i])
          }
        } else {
          photo.push(app.imageUrl + res.data.photo)
        }
        console.log(res)
        this.setData({
          id: res.data.id,
          safetyLevel: res.data.safetyLevel,
          categoryName : res.data.categoryName,
          address: res.data.address,
          type: res.data.categoryName,
          time: res.data.createTime,
          reporter: res.data.reportName,
          content: res.data.content,
          files: photo,
          video: res.data.video,
          videoSrc: app.imageUrl + res.data.video,
          categoryId: res.data.categoryId,
        })
      },
      fail: res => {
        dd.showToast({
          content: '网络异常！',
          type: 'fail'
        })
      },
      complete: () => {
        this.setData({
          loading: 0
        })
      }
    })
    this.setData({
      imageUrl: []
    })
    //清楚照片缓存
    dd.removeStorage({
      key: 'fileAndImg'
    })
  },

  previewImage: function(e) {
    if (this.data.files[0] != "/images/nophoto.png") {
      dd.previewImage({
        current: e.currentTarget.id, // 当前显示图片的http链接
        urls: this.data.files // 需要预览的图片http链接列表
      })
    }
  },
  onShow:function(e){
    this.setData({
      dealFiles : this.data.dealFiles,
      imageUrl : this.data.imageUrl
    })
  },
  // //自定义相机组件
  // toCamera:function(e){
  //   let level = 0
  //   switch (this.data.safetyLevel) {
  //     case 1:
  //       level = '安全'
  //       break
  //     case 2:
  //       level = '一般'
  //       break
  //     case 3:
  //       level = '危险'
  //       break
  //     case 4:
  //       level = '非常危险'
  //       break
  //     case 5:
  //       level = '巡检隐患'
  //       break
  //   }
  //   if(this.data.recordContent == undefined){
  //     this.setData({
  //       recordContent:''
  //     })
  //    }
  //   wx.navigateTo({
  //     url: '../../subpages/pages/cameraIdentified/cameraIdentified?address='+this.data.address+'&recordContent='
  //     +this.data.recordContent+'&type=5'+'&level='+level+'&category='+this.data.categoryName
  //   })
  // },

  chooseImage: function(e) {
    var that = this;
    dd.chooseImage({
      count: 3,
      sourceType: ['camera', 'album'], // 可以指定来源是相册还是相机，默认二者都有
      success: res => {
        dd.showLoading({
          content: "图片上传中"
        })
        let tempImg = res.tempFilePaths
        for (let i = 0; i < res.tempFilePaths.length; i++) {
          dd.uploadFile({
            url: app.baseUrl + '/DingDingSystem/fileUpload',
            filePath: res.tempFilePaths[i],
            fileName: 'file',
            fileType: 'image',
            header: {
              "Content-Type": "multipart/form-data"
            },
            success: res => {
              dd.hideLoading()
              if (res.data == "fail") {
                dd.showToast({
                  content: "图片上传失败",
                  type: "fail"
                })
              } else {
                dd.showToast({
                  content: "上传成功"
                })
                // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                that.setData({
                  dealFiles: that.data.dealFiles.concat(tempImg[i])
                })
                if (that.data.dealFiles.length == 3) {
                  that.setData({
                    hide: true
                  })
                }
                this.data.imageUrl.push(res.data)
              }
            },
            fail: res => {
              dd.hideLoading()
              dd.showToast({
                content: "图片上传失败",
                type: "fail"
              })
            }
          })
        }

      }
    })
  },

  previewImageDeal: function(e) {
    dd.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.dealFiles // 需要预览的图片http链接列表
    })
  },

  inputContent: function(e) {
    e.detail.value = app.trim(e.detail.value)
    this.setData({
      recordContent: e.detail.value,
      contentLength: parseInt(e.detail.value.length)
    })
  },

  formSubmit: util.throttle(function(e) {
    if (app.trim(e.detail.value.dealDetail) == "") {
      dd.showToast({
        content: "请输入现场问题描述",
        type: "fail"
      })
    } else if(this.data.imageUrl.length == 0 && this.data.dealVideo == ""){
      dd.showToast({
        title: "请附上处理照片或视频",
        type: "fail"
      })
    } else {
      let photo = ""
      for (let j = 0; j < this.data.imageUrl.length; j++) {
        photo += this.data.imageUrl[j]
        if (j != this.data.imageUrl.length - 1) {
          photo += ","
        }
      }
      dd.httpRequest({
        url: app.baseUrl + '/DingDingSystem/dealSafetyScene',
        method: 'POST',
        headers: {
          "Content-Type": "application/json"
        },
        data: JSON.stringify({
          safetyLevel: this.data.safetyLevel,
          safetySceneId: this.data.id,
          dealContent: this.data.recordContent,
          dealPhoto: photo,
          dealUser: app.globalData.userId,
          dealVideo: this.data.dealVideo
        }),
        dataType: 'json',
        success: res => {
          let that = this
          //---------------------------添加-----------------------------------------
          dd.confirm({
            title: '提示',
            content: '确认当前隐患处理完毕？',
            success(res) {
              if (res.confirm) {
                console.log('用户点击确定')
               //---------------------------------------gaolin添加-----------------------------------------
                 //根据上报人姓名获取绑定微信id
                 dd.httpRequest({
                  url:  app.baseUrl + '/DingDingSystem/getDingDingIdByReporterName',
                  method: 'GET',
                  dataType:'json',
                  data: {
                    reporterName: that.data.reporter,
                    schoolId: app.globalData.departmentId
                  },
                  success: res => {
                    if(res.data.res == 'success'){
                      let reporterWeChatId = res.data.msg
                      that.setData({
                        reporterWeChatId: reporterWeChatId,
                        reporterObject:{
                          res: res.data.res,
                          msg: res.data.msg
                        }
                      })
        
                    }
                  }
                })
      
                // 推送
                dd.httpRequest({
                  url: app.baseUrl + '/DingDingSystem/getAccessTokenForSendMsg',
                  method: 'GET',
                  data: {
                    schoolId: app.globalData.departmentId
                  },
                  dataType: 'json',
                  success: res => {
                    let access_token = res.data.access_token
                    dd.httpRequest({
                      url: app.baseUrl + '/DingDingSystem/getChargeManDingDingId',
                      method: 'POST',
                      headers: {
                        "Content-Type": "application/json"
                      },
                      data: JSON.stringify({
                        categoryId: that.data.categoryId,
                        schoolId: app.globalData.departmentId
                      }),
                      dataType: 'json',
                      success: res => {
                        let unbind = []
      
                        
                        for(let j=0; j<res.data.length; j++){
                          if(JSON.stringify(res.data).indexOf(JSON.stringify(that.data.reporterObject)) == -1){
                            res.data.push(that.data.reporterObject)
                            console.log("进入不相等")
                          }else{
                            console.log("进入相等")
                            break;
                          }
                        }
                        
      
                      
                        for (let i = 0; i < res.data.length; i++) {
                          if (res.data[i].res == "success") {
                            
                            let datetime = util.formatTime(new Date())
                            dd.httpRequest({
                              url: app.baseUrl + '/DingDingSystem/sendMessage',
                              method: 'POST',
                              headers:{
                                "Content-Type" : "application/json"
                              },
                              data: JSON.stringify({
                                schoolId: app.globalData.departmentId,
                                template: 1,
                                accessToken: access_token,
                                touser: res.data[i].msg,
                                safetySceneId: that.data.id,
                                data: {
                                  first: {
                                    value: `安全隐患已被${app.globalData.realname}处理`
                                  },
                                  keyword1: {
                                    value: that.data.reporter
                                  },
                                  keyword2: {
                                    value: datetime
                                  },
                                  keyword3: {
                                    value: `在${that.data.address}发现${that.data.type}类型隐患，请及时查看！`
                                  }
                                }
                              }),
                              dataType: 'json',
                              complete: () => {
                                that.setData({
                                  buttonused: true,
                                  buttonTitle: '已提醒',
                                })
                              }
                            });
                          } else {
                            //获取所有未绑定主管姓名
                            if(res.data[i].msg != ""){
                              unbind.push(res.data[i].msg)
                            }
                            
                          }
                        }
                        //提示未绑定信息
                        if (unbind.length != 0) {
                          let msg = unbind.join("、") + "主管未绑定服务号，无法正常接收推送！"
                          dd.showToast({
                            content: msg,
                          })
                        }
                      }
                    })
                  }
                })
                
                dd.reLaunch({
                  url: '/page/safetysence/safetysence'
                })
                dd.removeStorage({
                  key: 'fileAndImg'
                })
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })

        },
        fail: res => {
          dd.showToast({
            content: '网络异常！',
            type: 'fail'
          })
        }
      })
    }
  }),

  deleteImage: function(e) {
    let targetIndex = e.currentTarget.dataset.index
    let target = this.data.imageUrl[targetIndex]
    let temp = []
    let tempUrl = []
    let dealFilesLength = this.data.dealFiles.length
    for (let i = 0; i < this.data.dealFiles.length; i++) {
      if (i != targetIndex) {
        temp.push(this.data.dealFiles[i])
        tempUrl.push(this.data.imageUrl[i])
      }
    }
    dd.showActionSheet({
      items: ['删除这张照片'],
      success: res => {
        if (res.index != -1) {
          this.setData({
            dealFiles: temp,
            imageUrl: tempUrl
          })
          dd.setStorageSync({
            key: 'fileAndImg',
            data: {
              files : this.data.dealFiles,
              imgUrl : this.data.imageUrl
            }
          })
          dd.httpRequest({
            url: app.baseUrl + '/DingDingSystem/deleteFile',
            method: 'POST',
            headers:{
              "Content-Type" : "application/json"
            },
            data: JSON.stringify({
              filename: target.split("image/")[1]
            }),
            dataType: 'text',
            success: res => {
              if (dealFilesLength == 3) {
                this.setData({
                  hide: false
                })
              }
            }
          })
        }
      }
    })
  },
  //新增视频录制功能
  press:function (e) {
    dd.chooseVideo({
      sourceType: ['camera'],
      maxDuration: 10,
      success: res => {
        if(res.size > 2097152){
          dd.showToast({
            content: '文件大于2M！',
            type: "fail"
          })
        }else{
          dd.uploadFile({
            url: app.baseUrl + '/DingDingSystem/fileUpload2',
            filePath: res.tempFilePath,
            fileName: 'file',
            fileType: 'video',
            header: {
              "Content-Type": "multipart/form-data"
            },
            success:res=>{
              console.log(res.data)
              this.setData({
                dealVideoSrc: app.imageUrl+res.data,
                dealVideo: res.data
              })
            }
          })
        }
      },
      fail(res){
        console.log("-------调用失败")
      }
    })
  },
  delelteVideo:function(e) {
    let target = this.data.dealVideo
    console.log("dealVideo",target)
    dd.showActionSheet({
      items: ['删除视频'],
      success: res => {
        if (res.index != -1) {
          dd.httpRequest({
            url: app.baseUrl + '/DingDingSystem/deleteVideo',
            method: 'POST',
            headers:{
              "Content-Type" : "application/json"
            },
            data: JSON.stringify({
              filename: target.split("video/")[1]
            }),
            dataType: 'text',
            success: res => {
              if(res.data == "success"){
                this.setData({
                  dealVideo : ""
                })
              }
            }
          })
        }
      }
    })
  }
})